package com.qiantu.phone.ui.adapter;

import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.ui.uiutil.DeviceType;
import com.qiantu.phone.widget.DeviceEmptyView;
import com.qiantu.phone.widget.HomeAddDeviceView;
import com.qiantu.phone.widget.HomeCurtainBigView;
import com.qiantu.phone.widget.HomeDeviceBaseView;
import com.qiantu.phone.widget.HomeDeviceView;
import com.qiantu.phone.widget.HomeDimmingBigView;
import com.qiantu.phone.widget.HomeEnviromentView;
import com.qiantu.phone.widget.HomeFreshAirBigView;
import com.qiantu.phone.widget.HomeTemperatureBigView;
import com.qiantu.phone.widget.HomeTopSceneView;

import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Map;


/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2019/09/22
 * desc   : 房间标签数据列表
 */
public class HomeSceneDeviceAdapter extends BaseQuickAdapter<DeviceBean, BaseViewHolder> {

    public final static int TYPE_PAYLOAD_REFRESH_SCENE = 1;
    //需要设置大一点数字，避免跟DeviceType的ordinal重复
    private final static int TOP_TYPE = 11111;
    private final static int EMPTY_TYPE = 22222;
    private final static int NORMAL_TYPE = 33333;
    private final static int ENVIROMENT_TYPE = 44444;
    private final static int ADD_TYPE = 55555;
    private int smallHeight;
    private int lastMarginBottom;
    private int type;
    private String roomSerialNo;

    public HomeSceneDeviceAdapter(@Nullable List<DeviceBean> data, int type, String roomSerialNo) {
        super(0, data);
        smallHeight = AppApplication.getInstance().getResources().getDimensionPixelSize(R.dimen.dp_96);
        lastMarginBottom = AppApplication.getInstance().getResources().getDimensionPixelSize(R.dimen.dp_12);
        this.type = type;
        this.roomSerialNo = roomSerialNo;
    }

    @Override
    protected void convert(@NotNull BaseViewHolder holder, DeviceBean item) {
        StaggeredGridLayoutManager.LayoutParams sl = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
        if (sl == null) {
            sl = new StaggeredGridLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            holder.itemView.setLayoutParams(sl);
        }
        if (holder.itemView instanceof HomeEnviromentView) {
            ((HomeEnviromentView) holder.itemView).updateView(item.getHomeEnviroments());
            sl.setFullSpan(true);
        }else if (holder.itemView instanceof HomeTopSceneView) {
            ((HomeTopSceneView) holder.itemView).updateView(item.getHomeScenes());
            sl.setFullSpan(true);
        } else if (holder.itemView instanceof DeviceEmptyView) {
            View view = getRecyclerView().getChildAt(0);
            if(view != null){
                if(view instanceof HomeTopSceneView){
                    ((DeviceEmptyView) holder.itemView).updateView(!((HomeTopSceneView) view).hasScene());
                }
            }
            sl.setFullSpan(true);
        } else if (holder.itemView instanceof HomeDeviceBaseView) {
            ((HomeDeviceBaseView) holder.itemView).setDevice(item);
            int height = 0;
            if (item.getIsSwitch() && item.getHasCard() == 1) {//设备展开并且是可展开类型
                height = smallHeight * 2;
            } else {
                height = smallHeight;
            }
            int position = holder.getBindingAdapterPosition();
            if (position == getData().size() - 1) {
                sl.height = height + lastMarginBottom;
                sl.bottomMargin = lastMarginBottom;
            } else {
                sl.height = height;
                sl.bottomMargin = 0;
            }
        }else if(holder.itemView instanceof HomeAddDeviceView){
            int height = smallHeight;
            int position = holder.getBindingAdapterPosition();
            if (position == getData().size() - 1) {
                sl.height = height + lastMarginBottom;
                sl.bottomMargin = lastMarginBottom;
            } else {
                sl.height = height;
                sl.bottomMargin = 0;
            }
        }
    }

    @Override
    protected void convert(@NotNull BaseViewHolder holder, DeviceBean item, @NotNull List<?> payloads) {
        if (!payloads.isEmpty()) {
            Map<Integer, Object> payload = (Map<Integer, Object>) payloads.get(0);
            for (Integer key : payload.keySet()) {
                int type = key;
                if (holder.itemView instanceof HomeTopSceneView) {
                    if (type == TYPE_PAYLOAD_REFRESH_SCENE) {
                        ((HomeTopSceneView) holder.itemView).refreshSceneData();
                    }
                }
            }
        }
    }

    @Override
    protected BaseViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        if(viewType == ENVIROMENT_TYPE){
            view = new HomeEnviromentView(parent.getContext(), type, roomSerialNo);
        }else if (viewType == TOP_TYPE) {
            view = new HomeTopSceneView(parent.getContext(), type, roomSerialNo);
        } else if (viewType == EMPTY_TYPE) {
            view = new DeviceEmptyView(parent.getContext(), type, roomSerialNo);
        } else if (viewType == ADD_TYPE) {
            view = new HomeAddDeviceView(parent.getContext(), type, roomSerialNo);
        } else if (viewType == DeviceType.BREAKER_LIGHT.ordinal()) {
            view = new HomeDeviceView(parent.getContext(), type);
        } else if (viewType == DeviceType.ADJUST_LIGHT.ordinal()
                || viewType == DeviceType.TCT_DL.ordinal() || viewType == DeviceType.ADJUST_COLOR.ordinal()) {
            view = new HomeDimmingBigView(parent.getContext(), type);
        } else if (viewType == DeviceType.CURTAIN.ordinal()) {
            view = new HomeCurtainBigView(parent.getContext(), type);
        } else if (viewType == DeviceType.AIR_CONDITIONER.ordinal()
                || viewType == DeviceType.FLOOR_HEATING.ordinal()) {
            view = new HomeTemperatureBigView(parent.getContext(), type);
        } else if (viewType == DeviceType.FRESHAIR.ordinal()) {
            view = new HomeFreshAirBigView(parent.getContext(), type);
        } else if (viewType == NORMAL_TYPE) {
            view = new HomeDeviceView(parent.getContext(), type);
        } else {
            view = new HomeDeviceView(parent.getContext(), type);
        }
        return createBaseViewHolder(view);
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return ENVIROMENT_TYPE;
        }
        if (position == 1) {
            return TOP_TYPE;
        }
        DeviceBean device = getData().get(position);
        //手动添加的空设备占位的item
        if (position == 2 && position == getItemCount() - 1 && TextUtils.isEmpty(device.getDeviceSerialNo())) {
            return EMPTY_TYPE;
        }
        if(position == getItemCount() - 1 && device.getDeviceSerialNo() == null){
            return ADD_TYPE;
        }

        boolean isSwitch = device.getIsSwitch();
        String deviceType = device.getDeviceType();
        String type = device.getType();
        if (isSwitch && device.getHasCard() == 1) {
            if (deviceType.equals(DeviceType.BREAKER_LIGHT.stringType)) {
                return DeviceType.BREAKER_LIGHT.ordinal();
            } else if (deviceType.equals(DeviceType.ADJUST_LIGHT.stringType)) {
                return DeviceType.ADJUST_LIGHT.ordinal();
            } else if (deviceType.equals(DeviceType.TCT_DL.stringType) || deviceType.equals(DeviceType.ADJUST_LCT.stringType)) {
                return DeviceType.TCT_DL.ordinal();
            } else if (deviceType.equals(DeviceType.ADJUST_COLOR.stringType)) {
                return DeviceType.ADJUST_COLOR.ordinal();
            } else if (type.equals("curtain")) {
                return DeviceType.CURTAIN.ordinal();
            } else if (type.equals(DeviceType.AIR_CONDITIONER.stringType)) {
                return DeviceType.AIR_CONDITIONER.ordinal();
            } else if (type.equals(DeviceType.FLOOR_HEATING.stringType)) {
                return DeviceType.FLOOR_HEATING.ordinal();
            } else if (type.equals(DeviceType.FRESHAIR.stringType)) {
                return DeviceType.FRESHAIR.ordinal();
            } else {
                return NORMAL_TYPE;
            }
        } else {
            return NORMAL_TYPE;
        }
//        int type = -1;
//        if (!TextUtils.isEmpty(deviceType)){
//            type = Integer.parseInt(deviceType);
//        }
//        String deviceSubType = device.getSubType();
//        int subType = -1;
//        if (!TextUtils.isEmpty(deviceSubType)){
//            subType = Integer.parseInt(deviceSubType);
//        }
        //返回设备大类和小类（小类预留6位数）
//        return type * 100000 + subType;
    }

//    @Override
//    public void onViewAttachedToWindow(BaseViewHolder holder) {
//        int position = holder.getBindingAdapterPosition();
//        StaggeredGridLayoutManager.LayoutParams sl = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
//        if (holder.itemView instanceof HomeTopSceneView || holder.itemView instanceof DeviceEmptyView) {
//            sl.setFullSpan(true);
//        } else {
//            DeviceBean device = getData().get(position);
//            int height = 0;
////        //设备展开并且不是开关类型设备
////        if(device.isSwitch() && !DeviceType.SWITCH.stringType.equals(device.getDeviceType())){
//            if (device.isSwitch() && device.getHasCard() == 1) {//设备展开并且是可展开类型
//                height = smallHeight * 2;
//            } else {
//                height = smallHeight;
//            }
//            if (position == getData().size() - 1) {
//                sl.height = height + lastMarginBottom;
//                sl.bottomMargin = lastMarginBottom;
//            } else {
//                sl.height = height;
//                sl.bottomMargin = 0;
//            }
//        }
//        super.onViewAttachedToWindow(holder);
//    }

    @Override
    public long getItemId(int position) {
        DeviceBean device = getData().get(position);
        return device.hashCode();
    }

    public void update(DeviceBean newDevice) {
        //从1开始, 第0个是场景列表
        for (int i = 1; i < getData().size(); i++) {
            DeviceBean device = getData().get(i);
            //设备号相同并且deviceType相同才进入
            if (!TextUtils.isEmpty(device.getDeviceSerialNo())
                    && device.getDeviceSerialNo().equals(newDevice.getDeviceSerialNo())) {
                //在线状态不一样或者deviceType或者设备首页属性不一致才刷新
                if(device.getIsOnline() != newDevice.getIsOnline()
                        || !device.getImageUrl().equals(newDevice.getImageUrl())
                        || !device.getName().equals(newDevice.getName())
                        || !device.getRoomSerialNo().equals(newDevice.getRoomSerialNo())
                        || !device.getDeviceType().equals(newDevice.getDeviceType())
                        || !device.getStateData().getStatus().homeDeviceEquals(newDevice.getStateData().getStatus())){
                    getData().set(i, newDevice);
                    notifyItemChanged(i);
                }
                break;
            }
        }
    }

    public void update(List<DeviceBean> devices) {
        //从1开始, 第0个是场景列表
        for (int i = 1; i < getData().size(); i++) {
            DeviceBean device = getData().get(i);
            for(int j = 0; j<devices.size(); j++){
                if (!TextUtils.isEmpty(device.getDeviceSerialNo())
                        && device.getDeviceSerialNo().equals(devices.get(j).getDeviceSerialNo())) {
                    if(device.getIsOnline() != devices.get(j).getIsOnline()
                            || !device.getImageUrl().equals(devices.get(j).getImageUrl())
                            || !device.getName().equals(devices.get(j).getName())
                            || !device.getRoomSerialNo().equals(devices.get(j).getRoomSerialNo())
                            || !device.getDeviceType().equals(devices.get(j).getDeviceType())
                            || !device.getStateData().getStatus().homeDeviceEquals(devices.get(j).getStateData().getStatus())){
                        getData().set(i, devices.get(j));
                    }
                    break;
                }
            }
        }
    }
}